package com.flashcash.solu.app.base.presenter;

import android.util.Log;

import com.appsflyer.AppsFlyerLib;
import com.appsflyer.AppsFlyerProperties;
import com.flashcash.solu.app.base.BaseActivityView;
import com.flashcash.solu.bean.LoginTokenResponse;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.common.network.HttpErrorHandledSubScriber;
import com.flashcash.solu.common.network.ServiceGenerator;
import com.flashcash.solu.common.network.UserApi;
import com.hwangjr.rxbus.RxBus;
import com.x.leo.apphelper.log.XLog;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @作者:My
 * @创建日期: 2017/6/21 9:46
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class BaseActivityPresenterImpl implements BaseActivityPresenter {

    protected UserApi mUserApi = ServiceGenerator.createService(UserApi.class);
    protected BaseActivityView mView;
    protected boolean isAttached;


    @Override
    public void attach(BaseActivityView tBaseActivity) {
        mView = tBaseActivity;
        isAttached = true;
    }


    @Override
    public void disAttach() {
        mView = null;
        mUserApi = null;
        isAttached = false;
    }

    @Override
    public boolean isAttached() {
        return isAttached && mView != null;
    }


    public <T> Observable.Transformer<T, T> applySchedulers() {
        return new Observable.Transformer<T, T>() {

            @Override
            public Observable<T> call(Observable<T> tObservable) {
                return tObservable
                        .unsubscribeOn(Schedulers.io())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    @Override
    public void uploadXTrace() {
        if (isAttached()) {
        }
    }

    @Override
    public void showLoading(String string) {
        if (isAttached()) {
            Log.e("DataRefrash", "showLoading");
            mView.getBaseActivity().showLoading(string);
        }
    }

    @Override
    public void dismissLoading() {
        if (isAttached()) {
            Log.e("DataRefrash", "dismissLoading");
            mView.getBaseActivity().dismissLoading();
        }
    }

    @Override
    public void finish() {
        if (isAttached()) {
            mView.getBaseActivity().finish();
        }
    }


    @Override
    public void loginByAccountKit(String authorizationCode) {
        showLoading("");
        ServiceGenerator.createService(UserApi.class)
                .login_new(null, authorizationCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpErrorHandledSubScriber<LoginTokenResponse>() {
                    @Override
                    public void onFinalError(Throwable e) {
                        dismissLoading();
                        XLog.INSTANCE.e("login error:", e, 100);
                        if (isAttached) {
                            mView.onLoginError(e);
                        }
                    }

                    @Override
                    public void onNext(LoginTokenResponse loginTokenResponse) {
                        if (loginTokenResponse != null && loginTokenResponse.getToken() != null) {
                            XLog.INSTANCE.i(loginTokenResponse.getToken(), 10);
                            TokenManager.getInstance().setToken(loginTokenResponse.getToken(), 0);
                            TokenManager.getInstance().setMobile(loginTokenResponse.getMobile() == null ? "8000000000" : loginTokenResponse.getMobile());
                            RxBus.get().post(new EventCollection.AccoutUpdateEvent());

                            String appUserId = AppsFlyerProperties.getInstance().getString(AppsFlyerProperties.APP_USER_ID);
                            if (appUserId == null || appUserId.equals(""))
                                AppsFlyerLib.getInstance().setCustomerUserId(TokenManager.getInstance().getMobile());

                            AppsFlyerLib.getInstance().startTracking(mView.getBaseActivity().getApplication());

//                            Map<String,Object> eventValues = new HashMap<>();
//                            eventValues.put("mobile", TokenManager.getInstance().getMobile());
//                            AppsFlyerLib.getInstance().trackEvent(mView.getBaseActivity(), "af_login", eventValues);
//

//                            PushServiceFactory.getCloudPushService().bindAccount(TokenManager.getInstance().getMobile(), new CommonCallback() {
//                                @Override
//                                public void onSuccess(String s) {
//                                    XLog.INSTANCE.d("bind push service success", 10);
//                                }
//
//                                @Override
//                                public void onFailed(String s, String s1) {
//                                    XLog.INSTANCE.d("bind push service failed", 10);
//                                }
//                            });
                            dismissLoading();
                            if (isAttached) {
                                mView.onLoginSuccess();
                            }
                        } else {
                            onError(new IllegalStateException("null result"));
                        }
                    }


                });
    }

}
